package cat.joronya.supermanager.service;

import java.io.ByteArrayOutputStream;
import java.util.Hashtable;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import android.util.Log;
import cat.joronya.supermanager.Supermanager;

public class DayMatchesSync 
{
	// day matches GET
	private static final String DAYMATCHES_GET = "http://www.acb.com/resulcla.php?codigo=LACB-58&resultados=1&jornada=";
	
	// el client http on fer les peticions
	private DefaultHttpClient client = null;
	
	// jornada passada
	private Integer jornada = null;
	
	// hash per guardar team vs team
	protected Hashtable<String, String> dayMatches = null;
	
	public DayMatchesSync(DefaultHttpClient client, Integer jornada)
	{
		this.jornada = jornada;
		this.client = client;
	}
	
	/**
	 * Sync day matches from ACB web, no need for session.
	 */
	public void sync()
	{
		try
		{
			HttpGet plHttpGet = new HttpGet(DAYMATCHES_GET+jornada);
			HttpResponse response = client.execute(plHttpGet);

			ByteArrayOutputStream os = new ByteArrayOutputStream();
			response.getEntity().writeTo(os);
			String dayMatchesPage = os.toString(HTTP.ISO_8859_1);

			DayMatchesParser parser = DayMatchesParserProvider.getImpl(Package.getPackage("cat.joronya.supermanager.service.substrImpl"));
			//DayMatchesParser parser = DayMatchesParserProvider.getImpl(Package.getPackage("cat.joronya.supermanager.service.htmlcleanerImpl"));
			Log.d(Supermanager.TAG, "Start parsing day matches page...");
			long elapsedTime = parser.parse(dayMatchesPage);
			Log.d(Supermanager.TAG, "Stop parsing day matches page! Elapsed time: "+elapsedTime/1000);

			this.dayMatches = parser.getDayMatches();
		}
		catch(Exception e){}
	}
	
	public Hashtable<String, String> getDayMatches()
	{
		return dayMatches;
	}
}
